'use strict';
const dbc = require('../DBConfig/config');
const Controller = require("../core/base");
const JWT = require("jsonwebtoken");
const Model = require("../model/index");
const Sequelize = require("sequelize");

class UserController extends Controller {
    // 登录
    async login() {
        const { ctx } = this;
        const body = ctx.request.body;
        const data = await Model.UserList.findOne({
            where: {
                username: body.username
            }
        })
        if(!data) {
            return ctx.body = {
                code: 401,
                message: '用户不存在'
            }
        }
        if(data && (data.username !== body.username || data.password !== body.password)) {
            ctx.body = {
                code: 401,
                message: '用户名或密码不正确'
            }
            
        } else {
            const token = JWT.sign({
                userName: body.username,
            },
                this.config.jwt.secret, {
                expiresIn: 60 * 60 * 60000,
            });
            ctx.body = {
                code: 200,
                message: "success",
                body: {
                    token,
                    username: body.username
                }
            }
        }
    }
    // 获取轮播列表
    async bannerList() {
        const { ctx } = this;
        const body = ctx.request.query;
        try {
            const where = {};
            if(body.pos) {
                where.pos = body.pos;
            }
            const { count, rows } = await Model.BannerList.findAndCountAll({
                where: where,
                offset: (body.page - 1) * body.limit,
                limit: body.limit * 1
            })

            this.success({data: rows, total: count});
        } catch(err) {
            this.fail(err);
        }
    }
    // 添加轮播
    async bannerAdd() {
        const { ctx } = this;
        const body = ctx.request.body;
        try {
            await Model.BannerList.create({
                url: body.url,
                pos: body.pos,
                create_time: new Date(),
                update_time: new Date()
            })

            this.success();
        } catch(err) {
            this.fail(err);
        }
    }
    // 修改轮播
    async bannerEdit() {
        const { ctx } = this;
        const body = ctx.request.body;
        try {
            await Model.BannerList.update({
                url: body.url,
                pos: body.pos
            }, {
                where: {
                    id: body.id
                }
            })

            this.success();
        } catch(err) {
            this.fail(err);
        }
    }
    // 删除轮播
    async bannerDel() {
        const { ctx } = this;
        const body = ctx.request.body;
        try {
            await Model.BannerList.destroy({
                where: {
                    id: body.id
                }
            })
            this.success();
        } catch(err) {
            this.fail(err);
        }
    }
    // 获取景点列表
    async touristList() {
        const { ctx } = this;
        const body = ctx.request.query;
        try {
            let sql = `select * from tourist_place ${ body.name ? "where name like '" + body.name +"%'" : ""} limit ${(body.page - 1) * body.limit},${body.limit * 1}`;
            let sqlTotal = `select * from tourist_place ${ body.name ? "where name like '" + body.name +"%'" : ""}`;

            let query = await dbc.query(sql);
            let total = await dbc.query(sqlTotal);

            this.success({
                data: query[0] || [],
                total: total[0].length
            })
        } catch(err) {
            this.fail(err);
        }
    }
    // 景点详情
    async touristDetail() {
        const { ctx } = this;
        const body = ctx.request.query;
        try {
            let sql = `select a.*,b.banner,b.address,b.first_time,b.second_time from tourist_place a left join tourist_place_detail b on a.id=b.tourist_place_id where a.id=${body.id}`;
            let query = await dbc.query(sql);
            let result = query[0]

            this.success({...result[0]});
        } catch(err) {
            this.fail(err);
        }
    }
    // 添加景点
    async touristAdd() {
        const { ctx } = this;
        const body = ctx.request.body;
        const t = await dbc.transaction();
        try {
            let datas = await Model.TouristPlace.create({
                name: body.name,
                tag: body.tag,
                des: body.des,
                create_time: new Date(),
                update_time: new Date(),
                price: body.price,
                cover: body.cover,
                hot: body.hot,
                agent: body.agent,
                type: body.type,
                content: body.content,
                name_brief: body.name_brief
            }, { transaction: t });

            await Model.TouristPlaceDetail.create({
                tourist_place_id: datas.id,
                banner: body.banner,
                address: body.address,
                first_time: body.first_time,
                second_time: body.second_time
            }, { transaction: t })

            t.commit();
            this.success();
        } catch(err) {
            await t.rollback();
            this.fail(err);
        }
    }
    // 编辑景点
    async touristEdit() {
        const { ctx } = this;
        const body = ctx.request.body;
        const t = await dbc.transaction();
        try {
            await Model.TouristPlace.update({
                name: body.name,
                tag: body.tag,
                des: body.des,
                update_time: new Date(),
                price: body.price,
                cover: body.cover,
                hot: body.hot,
                agent: body.agent,
                type: body.type,
                content: body.content,
                name_brief: body.name_brief
            }, {
                where: {
                    id: body.id
                }
            }, { transaction: t });

            await Model.TouristPlaceDetail.update({
                banner: body.banner,
                address: body.address,
                first_time: body.first_time,
                second_time: body.second_time
            }, {
                where: {
                    tourist_place_id: body.id
                }
            }, { transaction: t })

            t.commit();
            this.success();
        } catch(err) {
            await t.rollback();
            this.fail();
        }
    }
    // 删除景点
    async touristDel() {
        const { ctx } = this;
        const body = ctx.request.body;
        const t = await dbc.transaction();
        try {
            await Model.TouristPlace.destroy({
                where: {
                    id: body.id
                }
            }, { transaction: t });

            await Model.TouristPlaceDetail.destroy({
                where: {
                    tourist_place_id: body.id
                }
            }, { transaction: t })

            t.commit();
            this.success();
        } catch(err) {
            await t.rollback();
            this.fail();
        }
    }

    // 保存行程规划
    async addTravel() {
        const { ctx } = this;
        const body = ctx.request.body;

        try {
            await Model.TouristPlaceDetail.update(
                {
                    travel_detail: body.detail
                },
                {
                    where: {
                        tourist_place_id: body.id
                    }
                }
            )

            this.success();
        } catch(err) {
            this.fail(err);
        }
    }

    // 获取行程详情
    async detailTravel() {
        const { ctx } = this;
        const body = ctx.request.query;

        try {
            let dataValues = await Model.TouristPlaceDetail.findOne({
                where: {
                    tourist_place_id: body.id
                }
            })
            this.success(dataValues&&dataValues.travel_detail || "")
        } catch(err) {
            this.fail(err);
        }
    }

    // 获取行程列表
    async travelList() {
        const { ctx } = this;
        const body = ctx.request.query;
        let where = {};
        try {
            let { count, rows } = await Model.StrategyList.findAndCountAll({
                attributes: [Sequelize.col("user.username"), "*"],
                include: [{
                    model: Model.UserList,
                    attributes: []
                }],
                where: where,
                offset: (body.page - 1) * body.limit,
                limit: body.limit * 1,
                raw: true
            })
            
            this.success({
                data: rows,
                total: count
            });
        } catch(err) {
            this.fail(err);
        }
    }

    // 删除单个行程
    async travelDel() {
        const { ctx } = this;
        const body = ctx.request.body;

        try {
            await Model.StrategyList.destroy({
                where: {
                    id: body.id
                }
            })
            this.success();
        } catch(err) {
            this.fail(err);
        }
    }
}

module.exports = UserController;
